package com.lagou.work.task03.angel.jobService.masterService;

import com.lagou.work.task03.angel.utils.ParsePropertiesFileUtil;

import java.util.*;

/**
 * @author：dingyuan
 * @date：2022.4.7 12:18
 * @description：模拟分布式计算-Master端功能抽象类
 * @version: 1.0
 */
public abstract class JobMasterBase {

    private static final String MASTER_CONFIG_NAME = "angle/master-";
    private static final String FILE_TYPE = ".properties";
    /**
     * @description：Master端入口
     * @param args
     * @throws Exception
     */
    public void run(String[] args) throws Exception {

        ArrayList<Map<String, String>> materConfigParam = loadMaterConfig(args);
        List<Integer> ports = Arrays.asList(Integer.valueOf(args[1]));

        handleJob(materConfigParam, ports);
    }

    /**
     * @description：加载master端配置文件
     * @param args
     * @throws Exception
     */
    public ArrayList<Map<String, String>> loadMaterConfig(String[] args) throws Exception {

        ArrayList<Map<String, String>> mapList = new ArrayList<>();
        if("SIT".equals(args[0])){
            Map<String, String> configMap = new ParsePropertiesFileUtil().readProperties(MASTER_CONFIG_NAME+"sit"+FILE_TYPE);
            LinkedHashSet<String> linkedHashSet = new LinkedHashSet();

            for (String s : configMap.keySet()) {
                linkedHashSet.add(s.split("\\.")[0]);
            }
            for (String set : linkedHashSet) {
                HashMap<String, String> map = new HashMap<>();
                for (String s : configMap.keySet()) {
                    if(s.contains(set)) {
                        map.put(s.contains("host") ? "server.host" : "server.port", configMap.get(s));
                    }
                }
                mapList.add(map);
            }
        }else {
            throw new Exception("The input env param{} is error, please check");
        }

        return mapList;
    }

    /**
     * @description：Master端任务管理实现
     * @param configMap
     * @throws Exception
     */
    public abstract void handleJob( ArrayList<Map<String, String>> configMap, List<Integer> port) throws Exception;
}
